package com.example.wastewater.controller;

import com.example.wastewater.common.biz.user.UserContext;
import com.example.wastewater.common.convention.result.Result;
import com.example.wastewater.common.convention.result.Results;
import com.example.wastewater.dto.req.UserLoginReqDTO;
import com.example.wastewater.dto.req.UserRegisterReqDTO;
import com.example.wastewater.dto.req.UserUpdateReqDTO;
import com.example.wastewater.dto.resp.UserActualRespDTO;
import com.example.wastewater.dto.resp.UserLoginRespDTO;
import com.example.wastewater.service.IUserService;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 *  用户管理控制层
 */
@RestController
@RequiredArgsConstructor
public class UserController {
    private final IUserService userService;

    /**
     *  用户注册
     */
    @PostMapping("/api/waste-water/admin/v1/user/register")
    private Result<Void> register(@RequestBody UserRegisterReqDTO requestParam){
        userService.register(requestParam);
        return Results.success();
    }

    /**
     *  修改用户信息
     */
    @PostMapping("/api/waste-water/admin/v1/user/edit")
    private Result<Void> update(@RequestBody UserUpdateReqDTO requestParam, ServletRequest servletRequest){
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String token = httpServletRequest.getHeader("token");
        userService.userInfoUpdate(requestParam, token);
        return Results.success();
    }

    /**
     *  用户登录
     */
    @PostMapping("/api/waste-water/admin/v1/user/login")
    private Result<UserLoginRespDTO> login(@RequestBody UserLoginReqDTO requestParam){
        return Results.success(userService.login(requestParam));
    }

    /**
     *  退出登录
     */
    @PostMapping("/api/waste-water/admin/v1/user/logout")
    private Result<Void> logout(ServletRequest servletRequest){
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String email = httpServletRequest.getHeader("email");
        String token = httpServletRequest.getHeader("token");
        userService.logout(email, token);
        return Results.success();
    }

    /**
     *  用户权限变更
     */
    @GetMapping("/api/waste-water/admin/v1/user/role-update")
    private Result<Void> roleUpdate(@Param("roleId") Integer roleId, @Param("email") String email){
        userService.roleUpdate(roleId, email);
        return Results.success();
    }

    /**
     *  获取所有用户
     */
    @GetMapping("/api/waste-water/admin/v1/user/all")
    private Result<List<UserActualRespDTO>> getAll(){
        return Results.success(userService.getAll());
    }

}
